package com.youyiwen.Service.impl;

import com.youyiwen.Bean.Notice;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.NoticeMapper;
import com.youyiwen.Mapper.UserMapper;
import com.youyiwen.Service.NoticeService;
import com.youyiwen.dto.NoticeDTO;
import com.youyiwen.dto.PageInitDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhaoyang
 * @Date: 2021/04/06
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInitDTO<NoticeDTO> showNotices(Integer page, Integer size, String userName) {
        PageInitDTO<NoticeDTO> pageInitDTO = new PageInitDTO<>();

        Integer totolCount = noticeMapper.selectNoticeCount(userName);


        if (totolCount == 0){
            totolCount = 1;
        }
        pageInitDTO.setPageInition(totolCount, page , size);
        if (page < 1){
            page = 1;
        }
        if(page > pageInitDTO.getTotalPage()){
            page = pageInitDTO.getTotalPage();
        }

        Integer offSet = size * ( page - 1 );

        List<Notice> notices = noticeMapper.selectNotice(userName,offSet,size);

        //返回一个questionDTOlist
        List<NoticeDTO> noticeDTOList = new ArrayList<>();
        for (Notice notice : notices) {
            NoticeDTO noticeDTO = new NoticeDTO();

            User user = userMapper.selectUserByName(notice.getUserName());
            noticeDTO.setNotice(notice);
            noticeDTO.setUser(user);
            noticeDTOList.add(noticeDTO);
        }
        pageInitDTO.setList(noticeDTOList);
        return pageInitDTO;
    }
}
